<template>
  <div class="address-edit">
    <div class="address-nav">
      <van-nav-bar
        title="新增收货地址"
        left-arrow
        @click-left="$router.go(-1)"
      />
    </div>
    <div class="address-form">
      <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        show-search-result
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        :tel-validator="validateMobile"
        @save="onSave"
        @delete="onDelete"
        :key="componentKey"
        :address-info="formData"
      />
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { areaList } from '@vant/area-data'
import { addAddress, getAddressDetail, deleteAddress, getDefaultAddressId, setDefaultAddress } from '@/api/address'
// import { getAreaList, editAddress } from '@/api/area'
export default {
  name: 'AddressEdit',
  data () {
    return {
      areaList,
      componentKey: 0,
      defaultId: '',
      areaListData: {},
      form: {
        name: '',
        phone: '',
        region: [
          {
            value: 1, // 必需 - 数值
            label: '北京市' // 必需 - 字符串
          },
          {
            value: 2,
            label: '北京市'
          },
          {
            value: 3,
            label: '东城区'
          }
        ],
        detail: ''
      },
      formData: {
        name: '',
        tel: '',
        province: '',
        city: '',
        county: '',
        addressDetail: '',
        isDefault: false
      }
    }
  },
  async created () {
    // this.getAreaList()
    this.getAddressDetailForEdit()
  },
  computed: {
    addressId () {
      return this.$route.query.addressId || ''
    }
  },
  methods: {
    // async getAreaList () { // 解构错误，导致无法获取市级列表
    //   try {
    //     const { data: { list } } = await getAreaList()
    //     this.areaListData = list
    //     const areaData = {
    //       province_list: {},
    //       city_list: {},
    //       county_list: {}
    //     }
    //     Object.values(this.areaListData).forEach(item => {
    //       const key = item.id
    //       if (item.level === 1) {
    //         // 省级
    //         areaData.province_list[key] = item.name
    //       } else if (item.level === 2) {
    //         // 市级
    //         areaData.city_list[key] = item.name
    //       } else if (item.level === 3) {
    //         // 区县
    //         areaData.county_list[key] = item.name
    //       }
    //     })
    //     this.areaList = areaData
    //   } catch (error) {
    //     console.error('获取市级列表失败', error)
    //   }
    //   // console.log('areaList:', this.areaList)
    // },
    async onSave (val) {
      // 验证省市区是否完整
      if (!val.province || !val.city || !val.county) {
        console.error('地址信息不完整:', { province: val.province, city: val.city, county: val.county })
        Toast('请选择完整的省市区信息')
        return
      }
      // 构建 regionArr
      // 创建用户，由于后台获取省市地址接口，与vant2组件库默认形式不一样，所以在获取region信息时,
      // value,直接接写成了1,2,3，需要重新构建数组，在async getAreaList ()方法中实现（发生错误，暂未实现）
      // const regionArr = [
      //   { value: this.findAreaId(val.province, 1), label: val.province },
      //   { value: this.findAreaId(val.city, 2), label: val.city },
      //   { value: this.findAreaId(val.city, 3), label: val.county }
      // ]
      const regionArr = [
        { value: 1, label: val.province },
        { value: 2, label: val.city },
        { value: 3, label: val.county }
      ]
      const postData = {
        form: {
          name: val.name,
          phone: val.tel,
          region: regionArr,
          detail: val.addressDetail
        }
      }
      console.log('提交数据:', postData)
      // console.log(val)
      if (!this.addressId) {
        // 新增地址
        await addAddress(postData)
        this.$router.replace({ name: 'addressList' })
      } else {
        // console.log(val)
        try {
          // 由于后台获取省市地址接口，与vant2组件库默认形式不一样，未成功获得id值，导致无法正常更新。
          // 所以暂时不更新地址信息，只更新默认地址
          // await this.getAddressDetailForEdit()
          // postData.form = detail
          // 修改地址
          // const res = await editAddress(this.addressId, postData)
          // console.log(res)
          if (val.isDefault) {
            // 设置默认地址
            await setDefaultAddress(this.addressId)
          }
          this.$router.replace({ name: 'addressList' })
        } catch (error) {
          console.error('Failed to edit address', error)
        }
      }
    },
    async getAddressDetailForEdit () {
      if (!this.addressId) return
      try {
        const { data: { detail } } = await getAddressDetail(this.addressId)
        // console.log('地址详情:', detail)
        const { data: { defaultId } } = await getDefaultAddressId()
        const region = detail.region || {}
        this.formData = {
          name: detail.name || '',
          tel: detail.phone || '',
          province: region.province || '',
          city: region.city || '',
          county: region.region || '',
          addressDetail: detail.detail || '',
          isDefault: defaultId === this.addressId
        }
        this.componentKey += 1
        // console.log('formData:', this.formData)
      } catch (error) {
        console.error('Failed to get address detail', error)
      }
    },

    // findAreaId (name, level) {
    //   if (!this.areaListData) return 0
    //   const area = Object.values(this.areaListData).find(
    //     item => item.name === name && item.level === level
    //   )
    //   return area ? area.id : 0
    // },

    async onDelete () {
      if (this.addressId) {
        await deleteAddress(this.addressId)
      }
      this.$router.replace({ name: 'addressList' })
    },
    validateMobile (phoneNum) {
      const isValid = /^1[3456789]\d{9}$/.test(phoneNum)
      if (!isValid) {
        this.$toast('请输入正确的11位手机号码')
      }
      return isValid
    }
  }
}

</script>

<style scoped lang="less">
.address-edit {
    display: flex;
    flex-direction: column;
    .address-nav{
      ::v-deep(.van-nav-bar__content){
        .van-nav-bar__title{
          font-weight: bold;
        }
      }
    }
   .address-form{
    ::v-deep(.van-cell){
      .van-switch--on{
        background-color: #ee0a24;
      }
    }
   }
}
</style>
